package controllers

import (
	"day02z/models"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
)

type WWW struct {
	beego.Controller
}

type Msg struct {
	gorm.Model
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (w *WWW) Add() {
	name := w.GetString("name")
	shou := w.GetString("shou")
	ke := w.GetString("ke")
	gua := w.GetString("gua")
	times := w.GetString("times")
	if name == "" || shou == "" || ke == "" || gua == "" || times == "" {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "字段不得为空",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	data := models.User{
		Name:  name,
		Shou:  shou,
		Ke:    ke,
		Gua:   gua,
		Times: times,
	}
	err := data.DataAdd(&data)
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	w.Data["json"] = Msg{
		Code: 200,
		Msg:  "添加成功",
		Data: data,
	}
	w.ServeJSON()
}
func (w *WWW) List() {
	page, _ := w.GetInt("page", 1)
	size, _ := w.GetInt("size", 3)
	offset := (page - 1) * size
	var err error
	var count int64
	var users []models.User
	models.DB.Model(&models.User{}).Count(&count)
	err = models.DB.Offset(offset).Limit(size).Find(&users).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "分页失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	PageData := make(map[string]interface{})
	PageData["count"] = count
	PageData["users"] = users
	w.Data["json"] = Msg{
		Code: 200,
		Msg:  "分页成功",
		Data: PageData,
	}
	w.ServeJSON()
}
